import fetch from 'dva/fetch';
import {extend, isObjectLike} from 'lodash';

const CONTENT_TYPE = 'Content-Type';
const JSON_TYPE = 'application/json';

/**
 * 默认http选项
 * @type {{headers: {}}}
 */
const DefaultOptions = {
    headers: {
        [CONTENT_TYPE]: JSON_TYPE,
    }
};

function parseJSON(response) {
    return response.json();
}

function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }

    const error = new Error(response.statusText);
    error.response = response;
    throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
    options = extend(DefaultOptions, options || {});
    if (options.body) {
        switch (options.method) {
        case 'get':
        case 'delete'://delete中body会被忽略
            //TODO:最佳到url中
            delete options.body;
            break;
        default:
            if (isObjectLike(options.body)) {
                options.body = JSON.stringify(options.body);
            }
            break;
        }
    }
    return fetch(url, options)
        .then(checkStatus)
        .then(parseJSON)
        .then(data => ({data}))
        .catch(err => ({err}));
}

const createMethod = (method) => (url, data, options) => {
    request(url, {method, body: data, ...options});
};

export const get = createMethod('get');

export const post = createMethod('post');

export const del = createMethod('delete');

export const put = createMethod('put');
